package com.qf.filter;

import com.qf.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 鉴权过滤器  判断消费者用户是否登录
 * 拦截所有请求，判断tomcat的session是否有用户对象信息
 * 如果有的话，就放行
 * 如果没有 说明用户没有登录  重定向到登录页面，重新登录
 */
@WebFilter("/*")
public class PremFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        获取用户的访问路径
        HttpServletRequest request =(HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
//        获取用户的访问路径
        String uriStr = request.getRequestURI();
        System.out.println("=======uriStr====" + uriStr);

        if (uriStr.lastIndexOf(".")>0){
            String extStr = uriStr.substring(uriStr.lastIndexOf("."));
            if (extStr !=null){
                if (".js".equals(extStr)){
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
        }
        if (uriStr.contains("/login") || uriStr.contains("/code")
                ||uriStr.contains("/user") || uriStr.contains("/register")
                || uriStr.contains("/type")|| uriStr.contains("/goods")
                || uriStr.contains("/index")
                || uriStr.contains(".css") || uriStr.contains("/admin")
                || uriStr.contains(".jpg") || uriStr.contains(".png")
                || uriStr.contains(".gif") || uriStr.contains(".eot")
                || uriStr.contains(".svg") || uriStr.contains(".ttf")
                || uriStr.contains(".woff") || uriStr.contains(".woff2")){
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
//        获取session对象
        HttpSession session = request.getSession();
//        判断绘画中是否有消费者用户的对象信息
        User user =(User) session.getAttribute("loginUser");

        if (user != null){
//         放行
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            response.sendRedirect("/login.jsp");
        }
    }
    @Override
    public void destroy() {

    }
}
